import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as todoActions from '../store/actions/todo.actions'
import { getIn } from 'immutable'

class Header extends Component {

  addTodo = (ev) => {
    if(ev.keyCode === 13){
      // 获取当前输入框的内容
      let taskName = ev.target.value
      console.log(taskName)
      if (taskName.trim().length === 0) {
        alert ('请输入任务名称')
        return
      } 
      // 触发新增任务
      this.props.add_todo(taskName)
      // 清空文本框
      ev.target.value = ''
    }
  }

  render() {
    // console.log(this.props, 'header')
    return (
      <header className="header">
        <h1>todos</h1>
        <input onKeyUp={this.addTodo} className="new-todo" placeholder="还有什么任务没有完成?" autoFocus />
      </header>
    );
  }
}

const mapDispatchToProps = (dispatch) => ({
  ...bindActionCreators(todoActions, dispatch)
})

const mapStateToProps = (state) => ({
  todos: getIn(state.todoReducer, ['todos'])
})

export default connect(mapStateToProps, mapDispatchToProps)(Header);
